#!/bin/bash

# JPY汇率检测系统安装脚本
# 适用于树莓派4B

set -e

echo "🚀 开始安装JPY汇率检测系统..."

# 检查是否为树莓派
if ! grep -q "Raspberry Pi" /proc/cpuinfo; then
    echo "⚠️  警告: 此脚本专为树莓派设计，在其他系统上可能无法正常工作"
fi

# 检查Python版本
PYTHON_VERSION=$(python3 --version 2>&1 | cut -d' ' -f2 | cut -d'.' -f1,2)
if [[ $(echo "$PYTHON_VERSION < 3.11" | bc -l) -eq 1 ]]; then
    echo "❌ 错误: 需要Python 3.11或更高版本，当前版本: $PYTHON_VERSION"
    exit 1
fi

# 设置项目目录
PROJECT_DIR="/home/pi/jpy2-cny"
SERVICE_USER="pi"

echo "📁 项目目录: $PROJECT_DIR"

# 创建项目目录
sudo mkdir -p "$PROJECT_DIR"
sudo chown $SERVICE_USER:$SERVICE_USER "$PROJECT_DIR"

# 复制项目文件
echo "📋 复制项目文件..."
sudo cp -r . "$PROJECT_DIR/"
sudo chown -R $SERVICE_USER:$SERVICE_USER "$PROJECT_DIR"

# 创建虚拟环境
echo "🐍 创建Python虚拟环境..."
cd "$PROJECT_DIR"
sudo -u $SERVICE_USER python3 -m venv venv
sudo -u $SERVICE_USER ./venv/bin/pip install --upgrade pip
sudo -u $SERVICE_USER ./venv/bin/pip install -r requirements.txt

# 创建日志目录
echo "📝 创建日志目录..."
sudo -u $SERVICE_USER mkdir -p "$PROJECT_DIR/logs"

# 复制systemd服务文件
echo "⚙️  配置systemd服务..."
sudo cp ops/systemd/jpy-rate.service /etc/systemd/system/
sudo cp ops/systemd/jpy-rate.timer /etc/systemd/system/

# 更新服务文件中的路径
sudo sed -i "s|/home/pi/jpy2-cny|$PROJECT_DIR|g" /etc/systemd/system/jpy-rate.service

# 重新加载systemd
sudo systemctl daemon-reload

# 启用并启动服务
echo "🚀 启动服务..."
sudo systemctl enable jpy-rate.service
sudo systemctl enable jpy-rate.timer
sudo systemctl start jpy-rate.service
sudo systemctl start jpy-rate.timer

# 检查服务状态
echo "📊 检查服务状态..."
sleep 5
sudo systemctl status jpy-rate.service --no-pager

echo ""
echo "✅ 安装完成！"
echo ""
echo "📋 服务管理命令:"
echo "  查看状态: sudo systemctl status jpy-rate.service"
echo "  查看日志: sudo journalctl -u jpy-rate.service -f"
echo "  重启服务: sudo systemctl restart jpy-rate.service"
echo "  停止服务: sudo systemctl stop jpy-rate.service"
echo ""
echo "🌐 访问地址:"
echo "  本地访问: http://localhost:8000"
echo "  局域网访问: http://$(hostname -I | awk '{print $1}'):8000"
echo ""
echo "📁 项目目录: $PROJECT_DIR"
echo "📝 日志目录: $PROJECT_DIR/logs"
echo ""
echo "🔧 配置文件:"
echo "  环境变量: $PROJECT_DIR/.env"
echo "  策略配置: $PROJECT_DIR/backend/policies/PolicyProfile.json"
echo ""
echo "⚠️  请确保:"
echo "  1. 配置正确的钉钉Webhook URL"
echo "  2. 检查防火墙设置，确保8000端口可访问"
echo "  3. 定期检查日志文件大小"
